package cn.ittaoli.utils;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lub_lenovo on 2017/8/21.
 */
public class ExcelUtils {

    public static Map<String, List<HSSFRow>> importExcel(String path){
        Map<String,List<HSSFRow>> map=new HashMap<>();


        try {
            InputStream is = new FileInputStream(path);
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

            // 循环工作表Sheet
            for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
                HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
                if (hssfSheet == null) {
                    continue;
                }

                List<HSSFRow> hssfRows=new ArrayList<>();

                // 循环行Row
                for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow == null) {
                        continue;
                    }

                    hssfRows.add(hssfRow);
//
//                    // 循环列Cell
//                    // "id","考生号","语文成绩","数学成绩","外语成绩"};
//                    String id = getValue(hssfRow.getCell(0));
//                    String ksh = getValue(hssfRow.getCell(1));
//                    String xm = getValue(hssfRow.getCell(2));
//                    String ywcj = getValue(hssfRow.getCell(3));
//                    String sxcj = getValue(hssfRow.getCell(4));
//                    String wycj = getValue(hssfRow.getCell(5));
//
//                    System.out.println(ksh+xm+ywcj+sxcj+wycj);

                }
                map.put(hssfSheet.getSheetName(),hssfRows);
            }
            return map;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    public static String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        }
        else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            // 返回数值类型的值
            return String.valueOf(hssfCell.getNumericCellValue());
        }
        else {
            // 返回字符串类型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }

    public static Integer transformType(String str){
        double v = Double.parseDouble(str);
        Integer res=new Double(v).intValue();
        return res;
    }
}
